package org.kymjs.kjframe.demo;


import static org.kymjs.kjframe.common.Constant.API_BASE;
import static org.kymjs.kjframe.common.Constant.CONTROL_BASE;
import static org.kymjs.kjframe.common.Constant.HEADER_AUTH_KEY;
import static org.kymjs.kjframe.common.Constant.HEADER_DEVICE_KEY;
import static org.kymjs.kjframe.common.Constant.TOKEN_PREFIX;
import static org.kymjs.kjframe.ui.ViewInject.toast;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.projection.MediaProjectionManager;
import android.net.LinkAddress;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import androidx.core.content.ContextCompat;

import com.google.android.material.textfield.TextInputEditText;
import com.google.gson.*;

import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.SupportActivity;
import org.kymjs.kjframe.auth.AuthManage;
import org.kymjs.kjframe.auth.Authuser;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.KJActivityStack;

public class MainActivity extends SupportActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int PERM_ACTION_ACCESSIBILITY_SERVICE = 100;
    private static final int PERM_MEDIA_PROJECTION_SERVICE = 101;
    private KJHttp httpClient = new KJHttp();
    private AppService appService = null;
    private AppServiceConnection serviceConnection = null;
    private SettingsHelper settingsHelper = null;
    private PermissionHelper permissionHelper;
    @BindView(id = R.id.startButton)
    private ToggleButton mBtnStart;
    @BindView(id = R.id.remoteControlEnableSwitch, click = true)
    private ToggleButton mSwtRemote;
    @BindView(id= R.id.inviteCodeInput)
    private TextInputEditText mInviteCode;

    private final CompoundButton.OnCheckedChangeListener mBtnStartListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (mInviteCode.getText() == null || mInviteCode.getText().length() < 6) {
                Toast.makeText(MainActivity.this, "邀请码长度不足6位", Toast.LENGTH_SHORT).show();

                mBtnStart.setOnCheckedChangeListener(null); // 取消监听，防止递归
                mBtnStart.setChecked(!isChecked);           // 恢复开关状态
                mBtnStart.setOnCheckedChangeListener(mBtnStartListener); // 恢复监听
                return;
            }
            if  (appService!=null && !appService.isAllowInviteCode()) {
                Toast.makeText(MainActivity.this, "投屏码不正确", Toast.LENGTH_SHORT).show();

                mBtnStart.setOnCheckedChangeListener(null); // 取消监听，防止递归
                mBtnStart.setChecked(!isChecked);           // 恢复开关状态
                mBtnStart.setOnCheckedChangeListener(mBtnStartListener); // 恢复监听
                return;
            }

            if (isChecked) {
                buttonView.setBackground(getDrawable(R.drawable.bg_button_on));
                mInviteCode.setEnabled(false);
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    if (appService != null) {
                        if (!appService.isAllowInviteCode()){
                            mInviteCode.setEnabled(true);
                        } else {
                            appService.castScreeningStart();
                        }
                    }
                }, 3000);
            } else {
                buttonView.setBackground(getDrawable(R.drawable.bg_button_off));
                mInviteCode.setEnabled(true);
                stop();
            }
        }
    };

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_main);
        if (!"org.kymjs.kjframe.demo".equals(getApplication().getPackageName())) {
            KJActivityStack.create().appExit(aty);
        }
    }

    @Override
    public void initWidget() {
        super.initWidget();
        initSettings();
        mInviteCode.setText(settingsHelper.getInviteCode());
        validateIpt();
//        赋值
        mBtnStart.setOnCheckedChangeListener(mBtnStartListener);
        mSwtRemote.setOnCheckedChangeListener((buttonView, isChecked) -> {
            buttonView.setBackground(getDrawable(isChecked ? R.drawable.bg_button_on :
                    R.drawable.bg_button_off));
            remoteControlEnable(isChecked);
        });
        if (settingsHelper.isRemoteControlEnabled())
            mSwtRemote.setChecked(true);
        if (AppService.isServiceRunning())
            setStartButton();
        initPermission();
        start();
    }

    public void validateIpt(){
        // 自定义过滤器：只允许 A-Z, a-z, 0-9
        InputFilter alphaNumFilter = (source, start, end, dest, dstart, dend) -> {
            StringBuilder filtered = new StringBuilder();
            for (int i = start; i < end; i++) {
                char c = source.charAt(i);
                if (String.valueOf(c).matches("[a-zA-Z0-9]")) {
                    filtered.append(c);
                } else {
                    toast("请输入英文大小写及汉字");
                }
            }
            return filtered.length() == (end - start) ? null : filtered.toString();
        };

// 限制最大长度为 6
        InputFilter lengthFilter = new InputFilter.LengthFilter(6);

        mInviteCode.setFilters(new InputFilter[]{alphaNumFilter, lengthFilter});
        mInviteCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                String code = s.toString();
                if (code.length() == 6){
                    if (appService != null ) {
                        appService.editInviteCode(code); // 输入合法且长度为6，执行逻辑
                        mInviteCode.setEnabled(false);
                        new Handler(Looper.getMainLooper()).postDelayed(() -> {
                            if (appService!=null && !appService.isAllowInviteCode()) {
                                mInviteCode.setEnabled(true);
                            }
                        }, 3000); // 延迟 3 秒再检查一次
                    }   else {
                        settingsHelper.setInviteCode(code);
                    }
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "Activity destroy");

        unbindService();
        uninitSettings();
        super.onDestroy();
    }

    private void start() {
        Log.d(TAG, "Stream start");
        if (AppService.isServiceRunning()) {
            bindService();
            return;
        }

        permissionHelper.requestInternetPermission();
    }

    private void stop() {
        Log.d(TAG, "Stream stop");
        if (!AppService.isServiceRunning())
            return;
        appService.castScreenStop();
    }

    private void initPermission() {
        permissionHelper = new PermissionHelper(this, new OnPermissionGrantedListener());
    }

    private class OnPermissionGrantedListener implements
            PermissionHelper.OnPermissionGrantedListener {
        @Override
        public void onAccessNetworkStatePermissionGranted(boolean isGranted) {
            if (!isGranted)
                return;
        }

        @Override
        public void onInternetPermissionGranted(boolean isGranted) {
            if (isGranted)
                permissionHelper.requestReadExternalStoragePermission();
            else
                resetStartButton();
        }

        @Override
        public void onReadExternalStoragePermissionGranted(boolean isGranted) {
            if (isGranted)
                permissionHelper.requestWakeLockPermission();
            else
                resetStartButton();
        }

        @Override
        public void onWakeLockPermissionGranted(boolean isGranted) {
            if (isGranted)
                permissionHelper.requestForegroundServicePermission();
            else
                resetStartButton();
        }

        @Override
        public void onForegroundServicePermissionGranted(boolean isGranted) {
            if (isGranted) {
                System.out.println("允许进行前台服务");
                //TODO permissionHelper.requestRecordAudioPermission();
                startService();
            }
            else
                resetStartButton();
        }

        @Override
        public void onRecordAudioPermissionGranted(boolean isGranted) {
            if (isGranted)
                startService();
            else
                resetStartButton();
        }

        @Override
        public void onCameraPermissionGranted(boolean isGranted) {
            if (isGranted)
                startService();
            else
                resetStartButton();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        permissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void startService() {
        Intent serviceIntent = new Intent(this, AppService.class);
        ContextCompat.startForegroundService(this, serviceIntent);
        serviceConnection = new AppServiceConnection();
        bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private void bindService() {
        Intent serviceIntent = new Intent(this, AppService.class);
        serviceConnection = new AppServiceConnection();
        bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private void unbindService() {
        if (serviceConnection == null)
            return;

        unbindService(serviceConnection);
        serviceConnection = null;
    }

    private class AppServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            AppService.AppServiceBinder binder = (AppService.AppServiceBinder)service;
            appService = binder.getService();
            if (!AppService.isServiceRunning())
                askMediaProjectionPermission();
            else
                setRemoteControlSwitch();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            appService = null;
            resetStartButton();
            Log.e(TAG, "Service unexpectedly exited");
        }
    }

    private void askMediaProjectionPermission() {
        MediaProjectionManager mediaProjectionManager = (MediaProjectionManager)
                getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(),
                PERM_MEDIA_PROJECTION_SERVICE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PERM_MEDIA_PROJECTION_SERVICE:
//                安卓本地8080服务暂不开启
                if (resultCode == RESULT_OK) {
                    if (!appService.initParams(data, getApplicationContext())) {
                        resetStartButton();
                        return;
                    }
                }
                else
                    resetStartButton();
                break;
            case PERM_ACTION_ACCESSIBILITY_SERVICE:
                if (isAccessibilityServiceEnabled())
                    enableAccessibilityService(true);
                else
                    resetRemoteControlSwitch();
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void setStartButton() {
        mBtnStart.setChecked(true);
    }

    private void resetStartButton() {
        mBtnStart.setChecked(false);
    }

    private void enableAccessibilityService(boolean isEnabled) {

        settingsHelper.setRemoteControlEnabled(isEnabled);
    }

    private void setRemoteControlSwitch() {
        mSwtRemote.setChecked(true);
    }

    private void resetRemoteControlSwitch() {
        mSwtRemote.setChecked(false);
    }

    private void remoteControlEnable(boolean isEnabled) {
        if (isEnabled) {
            if (!isAccessibilityServiceEnabled()) {
                startActivityForResult(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS),
                        PERM_ACTION_ACCESSIBILITY_SERVICE);
            } else {
                enableAccessibilityService(true);
            }
        } else {
            enableAccessibilityService(false);
        }

    }
    // 从系统设置中读取已启用的辅助功能服务列表
    // 如果列表不为空且包含我们指定的服务，就说明该服务已经启用
    private boolean isAccessibilityServiceEnabled() {
//        Context context = getApplicationContext();
//        ComponentName compName = new ComponentName(context, MouseAccessibilityService.class);
//        String flatName = compName.flattenToString();
//        String enabledList = Settings.Secure.getString(context.getContentResolver(),
//                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
//        return enabledList != null && enabledList.contains(flatName);
        return true;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.xml.menu_main, menu);
        return true;
    }

    public void initSettings() {
        settingsHelper = new SettingsHelper(getApplicationContext(), listener);
    }

    public void uninitSettings() {
        settingsHelper.close();
        settingsHelper = null;
    }

    private interface AuthCallback {
        void onResult(boolean success);
    }

    private SettingsHelper.SettingsChangeListener listener = new SettingsHelper.SettingsChangeListener() {
        @Override
        public void onInviteCodeChanged(String newInviteCode) {
            mInviteCode.setText(newInviteCode);
        }
    };

    public void checkAuth(AuthCallback callback){
        AuthManage manage = AuthManage.getInstance();
        String token = manage.getToken(this);
        if (token == null){
            callback.onResult(false);
        }
        HttpParams params = new HttpParams();
        params.putHeaders(HEADER_AUTH_KEY, TOKEN_PREFIX+token);
        httpClient.get(API_BASE+"/getinfo", params,
            new HttpCallBack() {
                @Override
                public void onSuccess(String t) {
                    super.onSuccess(t);
                    toast(t);
                    Gson gson = new Gson();
                    JsonObject jsonObject = JsonParser.parseString(t).getAsJsonObject();
                    JsonElement userElement = jsonObject.get("data");
                    Authuser user = gson.fromJson(userElement, Authuser.class);
                    manage.setLoggedInUser(aty, user);
                    callback.onResult(true);
                }

                @Override
                public void onFailure(int errorNo, String strMsg) {
                    super.onFailure(errorNo, strMsg);
                    callback.onResult(false);
                }
            });
    }

}
